package com.zoro.barn.business.service.pp.business.projectproduct.service;

import com.zoro.barn.business.service.pp.business.product.entity.BarnProduct;
import com.zoro.barn.business.service.pp.business.project.entity.BarnProject;
import com.zoro.barn.business.service.pp.business.projectproduct.entity.BarnProjectProduct;
import com.zoro.barn.business.service.pp.business.projectproduct.mapper.BarnProjectProductMapper;
import com.zoro.barn.business.service.pp.exceptions.DataIncompleteException;
import com.zoro.barn.commons.tools.string.IDs;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;

/**
 * @author zhaoxingwu
 */
@Service
public class BarnProjectProductService {

    @Resource
    private BarnProjectProductMapper barnProjectProductMapper;

    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(String projectId, String[] productIds) {

        if (StringUtils.isBlank(projectId) || productIds == null || productIds.length == 0) {
            throw new DataIncompleteException("project id and product ids can not be null");
        }

        Set<String> productSet = new HashSet<>(Arrays.asList(productIds));
        List<BarnProjectProduct> data = new ArrayList<>();
        for (String pid : productSet) {
            int has = this.barnProjectProductMapper.hasProduct(projectId, pid);
            if (has > 0) {
                continue;
            }
            BarnProjectProduct d = new BarnProjectProduct();
            d.setPid(IDs.uuid());
            d.setProjectId(projectId);
            d.setProductId(pid);
            data.add(d);
        }
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        this.barnProjectProductMapper.insertBatch(data);

    }

    public List<BarnProduct> getByProject(String projectId) {
        return this.barnProjectProductMapper.getByProject(projectId);
    }

    public List<BarnProject> getByProduct(String productId) {
        return this.barnProjectProductMapper.getByProduct(productId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String projectId, String productId) {
        barnProjectProductMapper.delete(projectId, productId);
    }
}
